import { authMiddleware } from '@/lib/api';
import {
  clientQueryAllPost,
  clientQueryAllSection,
  clientQuerySectionDetailsById,
  queryPath,
  queryPostRandom,
} from '@/services/api';
import { cookies } from 'next/headers';
import { createError, filterNumericParams, getMetadata } from '@/lib/tool';
import type {
  IPagination,
  IPath,
  IPost,
  ISectionClient,
  ISectionDetails,
} from '@/interfaces';
import HomePage from '@/app/[locale]/home/home';
import ResetPage from '@/app/[locale]/reset/reset';
import type { Metadata as MetadataNext } from 'next';
import { getTranslator } from 'next-intl/server';
import { getTranslatedFields } from '@/lib/dictionaries';

export async function generateMetadata({
  params: { locale },
}: {
  params: {
    locale: string;
  };
}): Promise<MetadataNext> {
  const t = await getTranslator(locale);
  return getMetadata({ title: t('commonPage.homePage') });
}

async function getData({
  searchParams,
}: {
  searchParams: {
    sectionId?: string;
    tagId?: string;
    sectionGroupId?: string;
  };
}) {
  try {
    const token = authMiddleware(cookies());
    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/',
      },
    });
    const req2 = clientQueryAllSection({
      baseURL: process.env.APP_API_SERVER,
      token,
    });
    const req3 = queryPostRandom({
      baseURL: process.env.APP_API_SERVER,
      token,
    });
    const req4 = clientQueryAllPost({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: searchParams,
    });

    const responses = await Promise.all([req1, req2, req3, req4]);
    const resp1 = await ((await responses[0]) as Response).json();
    const resp2 = await ((await responses[1]) as Response).json();
    const resp3 = await ((await responses[2]) as Response).json();
    const resp4 = await ((await responses[3]) as Response).json();

    const sections = resp2.data as ISectionClient[];
    const sectionId = searchParams.sectionId;
    let resp5;
    if (sectionId && sections.find((value) => value.id + '' === sectionId)) {
      resp5 = (await clientQuerySectionDetailsByIdReq({
        searchParams,
        token,
      })) as Response | undefined;
    }

    return {
      isSuccess: true,
      isError: false,
      data: {
        path: resp1.data as IPath,
        sections,
        randomPosts: resp3.data as IPost[],
        posts: resp4.data as IPagination<IPost>,
        sectionDetails: resp5
          ? ((await resp5.json()).data as ISectionDetails)
          : undefined,
        queryParams: searchParams,
      },
    };
  } catch (e: any) {
    return {
      isSuccess: false,
      isError: true,
      error: e,
    };
  }
}

export default async function Page({
  params: { locale },
  searchParams: { sectionId, sid, tagId, tid, sectionGroupId, sgid, v },
}: {
  params: { locale: string };
  searchParams: {
    sectionId?: string;
    sid?: string;
    tagId?: string;
    tid?: string;
    sectionGroupId?: string;
    sgid?: string;
    v?: 'h5';
  };
}) {
  const data = await getData({
    searchParams: filterNumericParams({
      sectionId: sectionId ?? sid,
      tagId: tagId ?? tid,
      sectionGroupId: sectionGroupId ?? sgid,
    }),
  });
  if (data.isError) {
    return <ResetPage error={createError(data.error)} />;
  }

  const source = data.data!;
  const translatedFields = await getTranslatedFields(locale, 'homePage');

  return <HomePage source={source} translatedFields={translatedFields} />;
}

const clientQuerySectionDetailsByIdReq = async ({
  searchParams,
  token,
}: {
  searchParams: { sectionId?: string };
  token: string | undefined;
}) => {
  const sectionId = searchParams.sectionId;
  if (!sectionId) {
    return;
  }

  return clientQuerySectionDetailsById({
    baseURL: process.env.APP_API_SERVER,
    token,
    id: sectionId,
    query: searchParams,
  });
};
